package com.cjkj.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cjkj.common.constant.EquipmentConstants;
import com.cjkj.common.core.controller.BaseController;
import com.cjkj.common.core.domain.AjaxResult;
import com.cjkj.common.core.page.TableDataInfo;
import com.cjkj.common.exception.ServiceException;
import com.cjkj.common.utils.StringUtils;
import com.cjkj.common.utils.http.HttpUtils;
import com.cjkj.equipment.domain.*;
import com.cjkj.equipment.domain.dto.EquipmentHistoryDataRequest;
import com.cjkj.equipment.domain.vo.EcgAnalysisData;
import com.cjkj.equipment.domain.vo.EcgVo;
import com.cjkj.equipment.domain.vo.TJ03RealTimeData;
import com.cjkj.equipment.service.*;
import com.cjkj.user.service.UserEquipmentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/equipment")
public class ApiController extends BaseController {

    @Resource
    private IEquipmentUsageRecordsService equipmentUsageRecordsService;

    @Resource
    private UserEquipmentService userEquipmentService;

    @Resource
    private IEquipmentMonitorRecordsService equipmentMonitorRecordsService;

    @Resource
    private IEquipmentMonitorRecordsRealtimeService equipmentMonitorRecordsRealtimeService;

    @Resource
    private IEquipmentService equipmentService;

    @Resource
    private EquipmentTj03MonitorRecordsEcgService ecgService;

    @Value("${cjkj.ecgUrl}")
    private String ecgUrl;

    /**
     * 获取绑定的设备
     * @param phone 手机号码
     * @return
     */
    @GetMapping(value = "/get")
    public AjaxResult get(String phone, String equipmentType) {
        EquipmentUsageRecords record = equipmentUsageRecordsService.getInUseByPhone(phone, equipmentType);
        if (record != null) {
            return AjaxResult.success(record);
        } else {
            return AjaxResult.error("未找到关联设备！");
        }
    }

    /**
     * 绑定设备
     * @param para
     * @return
     */
    @PostMapping(value = "/set")
    public AjaxResult set(@RequestBody Map<String, Object> para) {
        return userEquipmentService.userSetEquipment(para);
    }

    /**
     * 解绑设备
     * @param map
     * @return
     */
    @PostMapping(value = "unbound")
    public AjaxResult unbound(@RequestBody Map<String, String> map) {
        return userEquipmentService.unboundEquipment(map);
    }

    /**
     * 获取历史数据
     * @param request
     * @return
     */
    @GetMapping(value = "getHistory")
    public TableDataInfo getHistory(EquipmentHistoryDataRequest request) {
        EquipmentUsageRecords inUse = getUsage(request.getEquipmentNo(), request.getEquipmentType(), request.getPhone());
        Date useStartTime = inUse.getStartTime();
//        // 如果参数的开始时间小于设备使用时间，则从设备使用时间开始
//        Date paramStartTime = request.getStartTime();
//        if(paramStartTime != null && paramStartTime.before(useStartTime)) {
//            request.setStartTime(useStartTime);
//        }
        request.setStartTime(useStartTime);

        String equipmentType = request.getEquipmentType();

        if(EquipmentConstants.EQUIPMENT_TYPE_TJ02.equals(equipmentType)) {
            // 分页查询
            startPage();
            List<EquipmentMonitorRecords> list = equipmentMonitorRecordsService.getList(request);
            return getDataTable(list);
        }
        if(EquipmentConstants.EQUIPMENT_TYPE_TJ03.equals(equipmentType)) {
            // 分页查询
            startPage();
            List<EquipmentTJ03MonitorRecords> tj03Records = equipmentMonitorRecordsService.getTJ03Records(request);
            return getDataTable(tj03Records);
        }

        return getDataTable(Collections.emptyList());
    }

    /**
     * 查询实时数据
     * @param equipmentNo 设备编号
     * @param equipmentType 设备类型
     * @param phone 手机号
     * @return
     */
    @GetMapping(value = "getRealtimeData")
    public AjaxResult getRealtimeData(String equipmentNo, String equipmentType, String phone) {

        getUsage(equipmentNo, equipmentType, phone);

        Equipment equipment = equipmentService.getEquipment(equipmentNo, equipmentType);
        if(equipment == null) {
            return AjaxResult.error("设备不存在！");
        }

        EquipmentMonitorRecordsRealtime realtimeData = equipmentMonitorRecordsRealtimeService.getRealtimeData(equipmentNo);
        if(realtimeData != null) {
            realtimeData.setEquipmentStatus(equipment.getEquipmentStatus());
        }
        return AjaxResult.success(realtimeData);

    }

    /**
     * 查询TJ03实时数据
     * @param equipmentNo 设备编号
     * @param equipmentType 设备类型
     * @param phone 手机号
     * @return
     */
    @GetMapping(value = "getTj03RealtimeData")
    public AjaxResult getTj03RealtimeData(String equipmentNo, String equipmentType, String phone) {
        EquipmentUsageRecords inUse = getUsage(equipmentNo, equipmentType, phone);
        Equipment equipment = equipmentService.getEquipment(equipmentNo, equipmentType);
        if(equipment == null) {
            return AjaxResult.error("设备不存在！");
        }

        // 设备数据
        TJ03RealTimeData realtimeData = equipmentMonitorRecordsService.getTJ03RealtimeData(equipmentNo, inUse.getStartTime());
        realtimeData.setEquipmentStatus(equipment.getEquipmentStatus() == null ? 1: equipment.getEquipmentStatus());

        return AjaxResult.success(realtimeData);
    }

    @GetMapping(value = "getTj03RealtimeEcgData")
    public AjaxResult getTj03RealtimeEcgData(String equipmentNo, String equipmentType, String phone) {
        EquipmentUsageRecords inUse = getUsage(equipmentNo, equipmentType, phone);
        Equipment equipment = equipmentService.getEquipment(equipmentNo, equipmentType);
        if(equipment == null) {
            return AjaxResult.error("设备不存在！");
        }

        // 查询心电数据
        List<EcgVo> ecgDatas = ecgService.getEcgDatas(equipmentNo, inUse.getStartTime());
        TJ03RealTimeData realtimeData = new TJ03RealTimeData();
        realtimeData.setEcgData(ecgDatas == null? Collections.emptyList() : ecgDatas);

        if(ecgDatas != null && ! ecgDatas.isEmpty()) {
            // 获取心电并排序
            String ecgs = ecgDatas.stream()
                    .sorted(Comparator.comparing(EcgVo::getTime))
                    .map(EcgVo::getValue)
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));

            String resp = HttpUtils.sendPost(ecgUrl, "ecgs=" + ecgs);
            if(StringUtils.isNotBlank(resp)) {
                JSONObject jsonObject = JSON.parseObject(resp);
                Integer code = jsonObject.getInteger("code");
                if(0 == code) {
                    JSONObject result = jsonObject.getJSONObject("data");
                    if(result != null) {
                        EcgAnalysisData data = result.toJavaObject(EcgAnalysisData.class);
                        realtimeData.setEcgAnalysis(data);
                    }
                }
            }
        }

        return AjaxResult.success(realtimeData);
    }

    /**
     * 判断有没有在使用的设备
     * @param equipmentNo 设备号
     * @param equipmentType 设备类型
     * @param phone 电话号码
     */
    private EquipmentUsageRecords getUsage(String equipmentNo, String equipmentType, String phone) {
        EquipmentUsageRecords inUse = equipmentUsageRecordsService.getInUse(equipmentNo, equipmentType, phone);
        if(inUse == null) {
            throw new ServiceException("没有在使用的设备！");
        }
        return inUse;
    }

}
